<template>
    <div class="detail_container_template">
        <head-top signin-up="home"></head-top>
        <div class="project-desc-container">
            <el-row type="flex" justify="center" id="video-portal">
                <el-col :lg="14" :xl="14">
                    <div v-if="isVideoShow">
                        <youtube
                                v-if="isYoutuBe"
                                :video-id="videoId"
                                ref="youtube"
                                @playing="playing"
                                @paused="paused"
                                :player-vars="playerVars"
                        ></youtube>

                        <video v-else :src="campaign.pitchVideo" width="100%" height="360" controls="controls"></video>
                    </div>
                    <div v-else>
                        <img :src="campaign.pitchImage" width="100%" height="375px"/>
                    </div>

                </el-col>
                <el-col :lg="10" :xl="10">
                    <div class="desc-container">
                        <div class="tag">
                            <span>Funding</span>
                        </div>
                        <div class="seperator"></div>
                        <div class="title">
                            <span>{{campaign.title}}</span>
                        </div>
                        <div class="sub-title">
                            <span>{{campaign.tagline}}</span>
                        </div>
                        <div class="owner-info">
                            <p class="text">Project Owner</p>
                            <div class="detail">
                                <div class="icon" :style="getBGImage(campaign.ownerImage)"></div>
                                <div class="info">
                                    <p class="owner-name">
                                        <!--{{campaign.ownerName}}-->
                                        {{getUserNameById(campaign.ownerId)}}{{userName}}
                                    </p>
                                    <p class="owner-city">{{campaign.locationCity}},{{campaign.locationCountry}}</p>
                                </div>
                            </div>
                            <div class="campaign-info">
                                <div class="funding-detail">
                                    <span class="num">{{campaign.totalPrice}}</span>
                                    {{campaign.priceType}} Raised
                                </div>
                                <div class="progress" v-show="!isExpired">
                                    <el-progress :percentage="percentageShow" status="success"
                                                 :stroke-width="14"></el-progress>
                                </div>
                                <div class="percent-detail" v-show="!isExpired">
                                    <span class="num">{{percentage}}%</span>
                                    of {{campaign.price}} {{campaign.priceType}} fixed goal
                                    <span
                                            style="float: right;padding-right: 36px;"
                                    >{{campaign.campaignDuration | dateFormat}}</span>
                                </div>
                                <div class="percent-detail-expire" v-show="isExpired">
                                    <span class="num">{{percentage}}%</span>
                                    funded on {{new Date(campaign.campaignDuration).toLocaleDateString()}}
                                </div>
                                <div class="ope-area">
                                    <el-button size="small" type="danger" @click="addToBookmark()">Add To Bookmark
                                    </el-button>
                                </div>
                            </div>
                        </div>
                    </div>
                </el-col>
            </el-row>
        </div>


        <!--<el-row type="flex" v-if='"1" != version'>
            <el-col :lg="14" :xl="14" style="text-align: center">
                <div v-if="hasFeatureControl">
                    <el-button @click="clickFeatureShow">
                        <p v-if="isFeatureShow">
                            Click here to hide our risk assessment tools
                        </p>
                        <p v-else>
                            Click here to start exploring our risk assessment tools
                        </p>
                    </el-button>
                </div>
            </el-col>
        </el-row>-->


        <div class="feature-list-project-container" v-show='"1" != version'>
            <feature-list></feature-list>
        </div>

        <div class="extra-info">
            <el-row type="flex">
                <el-col :lg="14" :xl="14">
                    <div class="project-overview-container">
                        <div class="overview">
                            <div class="tag">
                                <span>Overview</span>
                            </div>
                            <div class="seperator"></div>
                        </div>
                        <div class="detail-info">
                            <div class="img-info" :style="getOverviewBGImage(campaign.overlayImage)"></div>
                            <div class="txt-info">
                                <p class="content" v-html="campaign.campaignOverview"></p>
                            </div>
                        </div>
                    </div>
                    <div class="project-extra-info-container">
                        <el-row type="flex" class="project-desc-container single-item" justify="center">
                            <el-col>
                                <project-extra-info-detail
                                        :campaign="campaignInfo"
                                        :campaignLoadStatus="loadStatus"
                                        :isBacker="isBacker"
                                ></project-extra-info-detail>
                            </el-col>
                        </el-row>
                    </div>
                </el-col>
                <el-col :lg="10" :xl="10">
                    <project-feature :peaksList="peaksList" :campaign="campaign"></project-feature>
                </el-col>
            </el-row>
        </div>

        <div class="interest-project-container">
            <div class="interest-item-container">
                <el-row type="flex" class="tag-container" justify="center">
                    <el-col>
                        <section class="single-row">
                            <h2>Tags for this project</h2>
                        </section>
                        <div class="seperator"></div>
                        <div class="tags-area">
                            <el-tag
                                    type="info"
                                    :key="index"
                                    v-for="(item, index) in campaign.tag"
                                    class="tag-item"
                            >{{item}}
                            </el-tag>
                        </div>
                    </el-col>
                </el-row>
            </div>
        </div>

        <!--<div class="interest-project-container">
                <div class="interest-item-container">
                    <el-row type="flex" class="project-desc-container" justify="center">
                        <el-col>
                            <section class="single-row">
                                <h2>You may also be interested in</h2>
                            </section>
                            <div class="seperator"></div>
                        </el-col>
                    </el-row>
                    <el-row type="flex" class="project-desc-container" justify="center">

                        <el-col>
                            <div class="single-item">
                                <el-row :gutter="20">
                                    <el-col :span="6" v-for="(item, index) in fundingItem" :key="index" type="flext"
                                            justify="content">
                                        <funding-item :fundingItem="item"></funding-item>
                                    </el-col>
                                </el-row>
                            </div>
                        </el-col>

                    </el-row>
                </div>

        </div>-->
    </div>
</template>

<script>
    import headTop from "components/header/head";
    import moment from "moment";
    import FundingItem from "components/common/fundingItem";
    import ProjectExtraInfoDetail from "./item/ProjectExtraInfoDetail";
    import ProjectFeature from "./item/ProjectFeature";
    import FeatureList from "./feature";
    import {mapState, mapMutations} from "vuex";
    import {apiQueryPeakByCID} from "@/api/peak";
    import {apiQueryUserPeakByCID} from "@/api/user_peak";
    import {queryCampaignInfoByID} from "@/api/campaign";
    import {saveBookmark} from "@/api/bookmark";
    import {saveUserLog} from "@/api/log";
    import Constants from "@/env";

    export default {
        data() {
            return {
                videoId: "",
                isVideoShow: true,
                isFeatureShow: false,
                hasFeatureControl: true,
                campaign: {},
                commentList: [],
                backerList: [],
                peaksList: [],
                campaignId: "",
                radio2: 1,
                isBacker: false,
                userName: "",
                percentage: 0,
                percentageShow: 0,
                pageSize: 10,
                loadStatus: false,
                commentTotalSize: 0,
                backerTotalSize: 0,
                playerVars: {
                    rel: 0
                },
                fundingItem: [
                    {
                        projectImage: "static/img/ex11.png",
                        title: "HiGame PC - Mini Workstation for Gamers & Creators",
                        desc:
                            "Latest Intel i7 w/ Radeon RX Vega M graphics, customisable RAM/storage & flexible I/O options.",
                        type: "MUSIC",
                        total: "340,176"
                    },
                    {
                        projectImage: "static/img/ex12.png",
                        title: "HiGame PC - Mini Workstation for Gamers & Creators",
                        desc:
                            "Latest Intel i7 w/ Radeon RX Vega M graphics, customisable RAM/storage & flexible I/O options.",
                        type: "MUSIC",
                        total: "340,176"
                    },
                    {
                        projectImage: "static/img/ex13.png",
                        title: "HiGame PC - Mini Workstation for Gamers & Creators",
                        desc:
                            "Latest Intel i7 w/ Radeon RX Vega M graphics, customisable RAM/storage & flexible I/O options.",
                        type: "MUSIC",
                        total: "340,176"
                    },
                    {
                        projectImage: "static/img/ex26.png",
                        title: "HiGame PC - Mini Workstation for Gamers & Creators",
                        desc:
                            "Latest Intel i7 w/ Radeon RX Vega M graphics, customisable RAM/storage & flexible I/O options.",
                        type: "MUSIC",
                        total: "340,176"
                    }
                ],
                queryText: "",
                isExpired: false,
                logScroll: false
            };
        },
        // 页面进入之前，请求数据
        beforeRouteEnter(to, from, next) {
            var campaignId = to.query.campaignId || "";

            if ("" == campaignId) {
                alert("Something goes wrong, Try again");
            } else {
                next(vm => {
                    // 通过 `vm` 访问组件实例
                    vm.campaignId = campaignId;
                    vm.$store.dispatch("SET_DRAW_STATUS", false);

                    vm.$store.dispatch("SET_CAMPAIGN_ID", campaignId);
                    vm.loadStatus = false
                    vm.$store
                        .dispatch("listCampaignByCID", campaignId)
                        .then(res => {
                            if (0 === res.code) {
                                // 如果查询成功
                                vm.loadStatus = true;
                                vm.campaign = res.campaign;

                                if (res.campaign.pitchVideo) {
                                    vm.videoId = vm.$youtube.getIdFromUrl(res.campaign.pitchVideo);
                                } else {
                                    vm.isVideoShow = false
                                }


                                if (res.campaign.tag) {
                                    vm.campaign.tag = res.campaign.tag.split(",");
                                }

                                if (res.campaign.category) {
                                    console.log("99999");
                                    vm.$store.dispatch(
                                        "SET_CURRENT_CATEGORY",
                                        res.campaign.category
                                    );
                                    vm.$store.dispatch("SET_DRAW_STATUS", true);
                                }
                                vm.percentage = parseFloat(
                                    ((vm.campaign.totalPrice / vm.campaign.price) * 100).toFixed(2)
                                );
                                vm.percentageShow = vm.percentage > 100 ? 100 : vm.percentage;

                                vm.isExpired =
                                    new Date(vm.campaign.campaignDuration) < new Date();
                                vm.isBacker = res.campaign.backer || false;
                            }
                        })
                        .catch(err => {
                            console.log(err);
                        });

                    apiQueryPeakByCID(campaignId)
                        .then(res => {
                            if (0 === res.code) {
                                // 如果查询成功
                                vm.peaksList = res.data.records;
                                // vm.campaign.tag = res.campaign.tag.split(",")
                            }
                        })
                        .catch(err => {
                            console.log(err);
                        });
                });
            }
        },

        beforeRouteLeave(to, from, next) {
             window.removeEventListener('scroll', this.handleScroll);
            $("#youtube_script").remove();
            console.log("**********")
            if (this.$refs.videoPlayer) {
                this.player.destroy();
            }
            next();
        },
        created() {
            window.addEventListener('scroll', this.handleScroll);
        },
        components: {
            headTop,
            FundingItem,
            ProjectExtraInfoDetail,
            ProjectFeature,
            FeatureList
        },

        computed: {
            ...mapState({
                currentName: state => state.user.name,
                version: state => state.user.version,
                userId: state => state.user.userId
            }),
            campaignInfo() {
                return this.campaign;
            },
            isYoutuBe() {
                var pitchVideo = this.campaign.pitchVideo || "";
                if ("" == pitchVideo) {
                    return true;
                } else {
                    return -1 != pitchVideo.indexOf("https://www.youtube.com");
                }
            },
            player() {
                console.log("1111")
                return this.$refs.youtube.player || null;
            }
        },

        methods: {
            handleScroll(e) {
                console.log("scoll exploer page")
                if (!this.logScroll) {
                    let totalHeight = $("#app").height();
                    let windowScroll = $(window).scrollTop();
                    if (windowScroll > (totalHeight * 0.5)) {
                        console.log("log explorer page")
                        this.logScroll = true
                        var tip = {
                            operation: "Scroll campaign page",
                            params: JSON.stringify({"userId":this.userId || 999999})

                        }

                        saveUserLog(tip);
                    }
                }

            },
            playVideo() {
                this.player.playVideo();
            },
            clickFeatureShow() {
                this.isFeatureShow = !this.isFeatureShow
                if (this.isFeatureShow) {
                    var tip2 = {
                        operation: "Explore_tools",
                        params: JSON.stringify({
                            "user": this.currentName,
                            "time": new Date().getTime(),
                            "campaignId": this.campaignId
                        })

                    }
                    saveUserLog(tip2);
                }

            },
            playing() {
                var tip = {
                    operation: "Play portal video",
                    params: JSON.stringify({
                        userId: this.userId,
                        campaignId: this.campaignId
                    })
                };

                saveUserLog(tip);
            },
            paused() {
                var tip = {
                    operation: "Pause portal video",
                    params: JSON.stringify({
                        userId: this.userId,
                        campaignId: this.campaignId
                    })
                };

                saveUserLog(tip);
            },
            stopCycle(event) {
                console.log("***");
            },
            async addToBookmark() {
                // 添加该项目到bookmark
                var that = this;
                var newComment = {
                    userId: this.userId,
                    campaignId: this.campaign.id
                };
                const res = await saveBookmark(newComment);
                // this.$store.dispatch('ADD_BOOKMARK', this.campaign)
                this.$message.success("add to bookmark success！");
            },

            getOverviewBGImage(imagePath) {
                return `background-image: url('${imagePath}');background-size: 100% 100%;
                background-repeat: no-repeat;`;
            },

            getBGImage(image) {
                // var imagePath = Constants.ICON_HOST + this.userId
                var imagePath = image;

                return `background-image: url('${imagePath}');background-size: 100% 100%;
                background-repeat: no-repeat;`;
            },
            getUserNameById(userId) {
                var that = this;

                userId = userId || "";
                if ("" == userId) {
                    that.userName = "Anonymity";
                    return;
                }

                var that = this;
                this.$store
                    .dispatch("getUserName", userId)
                    .then(res => {
                        that.userName = res.userName;
                    })
                    .catch(err => {
                    });
            },
            initLoad() {
                var that = this;

                $.each($("video"), function (index, item) {
                    if (null != item) {
                        item.addEventListener("play", function () {
                            if (1 == $(item).parents("#video-portal").length) {
                                var tip = {
                                    operation: "Play portal video",
                                    params: JSON.stringify({
                                        userId: that.userId,
                                        campaignId: that.campaignId
                                    })
                                };
                            } else {
                                var tip = {
                                    operation: "Play story video",
                                    params: JSON.stringify({
                                        userId: that.userId,
                                        campaignId: that.campaignId
                                    })
                                };
                            }

                            saveUserLog(tip);
                        });

                        item.addEventListener("pause", function () {
                            if (1 == $(item).parents("#video-portal").length) {
                                var tip = {
                                    operation: "Pause portal video",
                                    params: JSON.stringify({
                                        userId: that.userId,
                                        campaignId: that.campaignId
                                    })
                                };
                            } else {
                                var tip = {
                                    operation: "Pause story video",
                                    params: JSON.stringify({
                                        userId: that.userId,
                                        campaignId: that.campaignId
                                    })
                                };
                            }

                            saveUserLog(tip);
                        });
                    }
                });
            }
        },
        filters: {
            dateFormat(time) {
                return moment(time)
                    .startOf("mimute")
                    .fromNow();
            }
        },
        mounted() {
            /*console.log("绑定")
                    window.onYouTubeIframeAPIReady = function() {
                        console.log("onYouTubeIframeAPIReady")
                        alert("dd")
                    }
                    console.log("绑定")*/
        },
        watch: {
            loadStatus(newValue, oldValue) {
                var that = this;
                if (true == newValue) {
                    setTimeout(function () {
                        that.initLoad();
                    }, 2000);
                }
            }
        }
    };
</script>

<style lang="scss" scoped>
    @import "../../style/mixin";

    .head_logo {
        left: 0.4rem;
        font-weight: 400;
        @include sc(0.7rem, #fff);
        @include wh(2.3rem, 0.7rem);
        @include ct;
    }

    .detail_container_template {
        background-color: white;
        .seperator {
            width: 100%;
            height: 2px;
            background-color: #dddddd;
            margin-top: 6px;
            margin-bottom: 6px;
        }

        .siteLogo {
            svg {
                height: 24px;
                width: 160px;
                fill: #eb1478;
            }
        }
        .single-row {
            padding: 0 16px;
        }
        .project-extra-info-container {
            margin-top: 26px;
            min-height: 600px;
        }
        .project-desc-container {
            margin-top: 26px;
            padding-left: 26px;
            .desc-container {
                padding-left: 26px;
                .tag {
                    span {
                        text-transform: uppercase;
                        color: #088366;
                        letter-spacing: 1px;
                        font-size: 14px;
                    }
                }
                .seperator {
                    width: 100%;
                    height: 2px;
                    background-color: #dddddd;
                    margin-top: 6px;
                    margin-bottom: 6px;
                }
                .title {
                    font-family: "Benton Sans Medium";
                    font-size: 28px;
                    line-height: 35px;
                    letter-spacing: 0;
                    font-weight: normal;
                    color: #2a2a2a;
                    margin-bottom: 16px;
                }
                .sub-title {
                    font-family: "Benton Sans", "Helvetica", "sans-serif";
                    font-size: 20px;
                    line-height: 26px;
                    letter-spacing: 0;
                    font-weight: normal;
                    color: #6a6a6a;
                }
                .owner-info {
                    margin-top: 30px;
                    .text {
                        margin-bottom: 10px;
                        text-transform: uppercase;
                        color: #6a6a6a;
                        font-family: "Benton Sans Medium";
                        font-size: 11px;
                        line-height: 14px;
                        letter-spacing: 1px;
                    }
                    .detail {
                        display: flex;
                        align-items: center;
                        margin-bottom: 30px;
                        .icon {
                            width: 40px;
                            height: 40px;
                            border-radius: 26%;
                            background: url("~assets/profile.png") no-repeat;
                            background-size: 100% 100%;
                        }
                        .info {
                            margin-left: 16px;
                            font-family: "benton-sans", "Helvetica", "sans-serif";
                            .owner-name {
                                color: #2a2a2a;
                                font-weight: bold;
                                margin-top: 6px;
                                margin-bottom: 2px;
                                margin-left: 6px;
                            }
                        }
                    }
                }
                .campaign-info {
                    .funding-detail {
                        margin-bottom: 6px;
                        .num {
                            color: black;
                            font-weight: bold;
                            font-size: 18px;
                        }
                    }
                    .progress {
                        width: 100%;
                    }

                    .percent-detail-expire {
                        margin-top: 6px;
                        font-size: 16px;
                        .num {
                            color: black;
                            font-weight: bold;
                        }
                    }

                    .percent-detail {
                        margin-top: 6px;
                        .num {
                            color: black;
                            font-weight: bold;
                        }
                    }
                    .ope-area {
                        padding-top: 6px;
                    }
                }
            }
        }

        .project-overview-container {
            padding-left: 26px;
            .overview {
                margin-top: 46px;
                .tag {
                    span {
                        text-transform: uppercase;
                        letter-spacing: 1px;
                        font-size: 16px;
                        color: #6a6a6a;
                        margin-top: 20px;
                        margin-bottom: 20px;
                        padding-top: 5px;
                        padding-bottom: 5px;
                    }
                }
                .seperator {
                    width: 100%;
                    height: 2px;
                    background-color: #dddddd;
                    margin-top: 6px;
                    margin-bottom: 6px;
                }
            }
            .detail-info {
                display: flex;
                margin-top: 10px;
                .img-info {
                    width: 247px;
                    height: 285px;
                    /*background: url('/static/img/test.jpg') no-repeat;*/
                    background-size: 100% 100%;
                    background-repeat: no-repeat;
                }
                .txt-info {
                    flex: 1;
                    padding-left: 26px;
                    .content {
                        font-size: 16px;
                        font-weight: normal;
                        line-height: 24px;
                    }
                }
            }
        }
        .interest-project-container {
            background-color: #f5f5f5;
            border-bottom: 1px solid #dddddd;
            border-top: 1px solid #dddddd;
            padding: 26px 0px;
            margin-top: 26px;
            .interest-item-container {
                flex: 1;
                .single-item {
                    margin: 26px;
                }
                .tag-container {
                    margin-bottom: 26px;
                    padding-left: 26px;
                    .tags-area {
                        margin-top: 16px;
                        .tag-item {
                            margin-left: 16px;
                            text-transform: uppercase;
                        }
                    }
                }
            }
        }
    }
</style>